<template>
    <div v-if="!isSubmitSuccess">
        <div class="content-detail">
            <BaseInfo v-if="detailType == 'look'" :info="baseInfo" :type="detailType" />
            <!-- 商户信息 -->
            <EnterpriseInfo
                ref="enterpriseInfoRef"
                v-model="corp_info"
                :disabled="formDisabled"
                @ocrChange="corpLicenseOCR" />
            <!-- 账户信息 -->
            <EnterpriseAccountInfo
                ref="enterpriseAccountInfoRef"
                v-model="account_info"
                :corpMainType="corp_info.corp_main_type"
                :disabled="formDisabled" />
            <!-- 法人信息 -->
            <LegalPersonInfo
                ref="legalPersonInfoRef"
                v-model="lp_info"
                :corpMainType="corp_info.corp_main_type"
                :disabled="formDisabled" />
            <!-- 联系人信息 -->
            <ContactsInfo
                ref="contactsInfoRef"
                v-model="contact_info"
                :corpMainType="corp_info.corp_main_type"
                :disabled="formDisabled" />
            <!-- 控制人信息 -->
            <EnterpriseControllerInfo
                ref="enterpriseControllerRef"
                v-model="ctl_info"
                :corpMainType="corp_info.corp_main_type"
                :disabled="formDisabled" />
            <!-- 受益人信息 -->
            <EnterpriseBeneficiaryInfo
                ref="enterpriseBeneficiaryRef"
                v-model="ben_info"
                :corpMainType="corp_info.corp_main_type"
                :disabled="formDisabled" />
        </div>
        <div class="footer-info">
            <el-button v-if="detailType == 'look'" type="primary" @click="onBackList">返回列表</el-button>
            <template v-else-if="detailType == 'edit' && noDraft">
                <el-button @click="onBack">取消</el-button>
                <el-button type="primary" @click="onSubmitData">保存并提交</el-button>
            </template>
            <template v-else>
                <el-button @click="onBack">取消</el-button>
                <el-button plain type="primary" @click="onSaveDraft">保存为草稿</el-button>
                <el-button type="primary" @click="onSubmitData">提交资料</el-button>
            </template>
        </div>
    </div>
    <DataSubmitSuccess v-else @submit="onInReview" />
</template>
<script setup>
import BaseInfo from './BaseInfo.vue';
import EnterpriseInfo from './EnterpriseInfo.vue';
import EnterpriseAccountInfo from './EnterpriseAccountInfo.vue';
import LegalPersonInfo from './LegalPersonInfo.vue';
import ContactsInfo from './ContactsInfo.vue';
import EnterpriseControllerInfo from './EnterpriseControllerInfo.vue';
import EnterpriseBeneficiaryInfo from './EnterpriseBeneficiaryInfo.vue';

import DataSubmitSuccess from './DataSubmitSuccess.vue';

import { ElMessage, ElMessageBox } from 'element-plus';

import { ref, reactive, onMounted, computed, onUnmounted, nextTick, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { cloneDeep } from 'lodash';
import { throttle } from '@/commons/utils';
import request from '@/request/index';

const route = useRoute();
const router = useRouter();

/** 企业信息ref */
const enterpriseInfoRef = ref(null);

/** 企业账户信息ref */
const enterpriseAccountInfoRef = ref(null);

/** 法人信息ref */
const legalPersonInfoRef = ref(null);

/** 联系人信息ref */
const contactsInfoRef = ref(null);

/** 企业控制人信息ref */
const enterpriseControllerRef = ref(null);

/** 企业受益人信息ref */
const enterpriseBeneficiaryRef = ref(null);

/** 是否展示提交审核中box */
const isSubmitSuccess = ref(false);

/** 详情id */
const detailId = ref(route.query.id);

const routeList = {
    '/pay/account/create': 'new',
    '/pay/account/edit': 'edit',
    '/pay/account/view': 'look'
};
let routeUrlCode = route.fullPath.split('?')?.[0];

const detailType = ref(routeList[routeUrlCode]);

/** 表单禁用 */
const formDisabled = computed(() => {
    return detailType.value == 'look';
});

const noDraft = computed(() => {
    return baseInfo.value.status != 10;
});

let isp_code = route.query?.isp_code;
// 产品能力
let capacity_code = route.query?.capacity_code;

const baseInfo = ref({
    status: 10
});

/** 商户信息 */
const corp_info = reactive({
    corp_main_type: route.query?.corp_main_type || 1,
    corp_license: '',
    corp_name: '', //企业名称
    corp_abbreviation: '', //企业简称
    corp_unified_social_credit_code: '', //统一社会信用代码
    corp_reg_area: '', //注册地区
    corp_reg_address: '', //注册地址
    corp_license_term_start: '', //营业期限开始日期
    corp_license_term_end: '', //营业期限结束日期
    corp_license_is_long: '2', //营业期限是否长期 1-是 2-否
    corp_category: '', //经营类目
    corp_industry: '', //所属行业
    corp_industry_name: '',
    corp_scope: '', //经营范围
    corp_site_name: '暂无', //公司网站名称
    corp_icp_number: '暂无', //ICP备案号
    corp_capital: '', //注册资本
    corp_composition: '', // 组成形式 1-个人经营 2-家庭经营 【corp_main_type=2时必填】
    corp_times: [],
    corp_license_place: [], //营业场所照片
    corp_door: '' //门头照
});

/** 账户信息 */
const account_info = reactive({
    account_type: 1, // 账户类型 1-对公账户 2-经营者对私账户【corp_main_type=2时必填】
    account_name: '', //对公账户名称
    account_public: '', //对公账户号
    account_bank: '', //对公账户开户行信息
    account_license: '', //开户许可证图片
    account_settle_type: '', //结算时间类型 1-次工作日结算（T1） 2-次自然日结算（D1）
    account_pay_rate: 30, //支付费率（单位：分）
    account_private: '', //对私银行卡卡号【corp_main_type=2 && account_type=2时必填】
    account_bank_private: '', //对私银行卡开户行信息【corp_main_type=2 && account_type=2时必填】
    account_license_private: '' //银行卡卡面【corp_main_type=2 && account_type=2时必填】
});

/** 法人信息 */
const lp_info = reactive({
    lp_id_card_front: '', //法人身份证人像面
    lp_id_card_back: '', //法人身份证国徽面
    lp_name: '', //法人姓名
    lp_id_card: '', //法人身份证号码
    lp_id_card_start: '', //法人身份证有效期开始日期
    lp_id_card_end: '', //法人身份证有效期结束日期
    times: [],
    lp_id_card_is_long: 2, //法人身份证有效期是否长期 1-是 2-否
    lp_id_card_area: '', //法人身份证归属地区
    lp_id_card_address: '' //法人身份证地址
});

/** 联系人信息 */
const contact_info = reactive({
    contact_is_lp: 2, //联系人是否为法人 1-是 2-否
    contact_id_card_front: '', //联系人身份证人像面【contact_is_lp = 2 时必填】
    contact_id_card_back: '', //联系人身份证国徽面【contact_is_lp = 2 时必填】
    contact_name: '', //联系人姓名【contact_is_lp = 2 时必填】
    contact_id_card: '', //联系人身份证号码【contact_is_lp = 2 时必填】
    contact_id_card_start: '', //联系人身份证有效期开始日期【contact_is_lp = 2 时必填】
    contact_id_card_end: '', //联系人身份证有效期结束日期【contact_is_lp = 2 时必填】
    times: [],
    contact_id_card_is_long: 2, //联系人身份证有效期是否长期 1-是 2-否【contact_is_lp = 2 时必填】
    contact_email: '', //联系人邮箱【contact_is_lp = 2 时必填】
    contact_mobile: '', //联系人手机号【contact_is_lp = 2 时必填】
    contact_agent_loa: '', //代理人委托书图片
    lp_email: '', //法人邮箱
    lp_mobile: '' //法人手机号
});

/** 控制人信息 */
const ctl_info = reactive({
    ctl_is_lp: 2, //实际控制人是否为法人
    ctl_type: 1, //实际控制人类型 1-个人 2-企业
    ctl_id_card_front: '', //实际控制人身份证人像面【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card_back: '', //实际控制人身份证国徽面【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_name: '', //实际控制人姓名【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card: '', //实际控制人身份证号码【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card_start: '', //实际控制人身份证有效期开始日期【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card_end: '', //实际控制人身份证有效期结束日期【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_times: [],
    ctl_id_card_is_long: 2, //实际控制人身份证有效期是否长期 1-是 2-否【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card_area: '', //实际控制人身份证归属地区【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_id_card_address: '', //实际控制人身份证地址【ctl_is_lp=2 && ctl_type=1时 必填 】
    ctl_corp_license: '', //实际控制企业营业执照图片【ctl_is_lp=2 && ctl_type=2时 必填 】
    ctl_corp_name: '', //实际控制企业名称【ctl_is_lp=2 && ctl_type=2时 必填 】
    ctl_corp_unified_social_credit_code: '', //实际控制企业统一社会信用代码【ctl_is_lp=2 && ctl_type=2时 必填 】
    ctl_corp_license_term_start: '', //实际控制企业营业期限开始日期【ctl_is_lp=2 && ctl_type=2时 必填 】
    ctl_corp_license_term_end: '', //实际控制企业营业期限结束日期【ctl_is_lp=2 && ctl_type=2时 必填 】
    ctl_corp_times: [],
    ctl_corp_license_term_is_long: '2' //实际控制企业营业期限是否长期 1-是 2-否
});

/** 受益人信息 */
const ben_info = reactive({
    ben_is_lp: 2, //实际受益人是否为法人 1-是 2-否
    ben_id_card_front: '', //实际受益人身份证人像面【ben_is_lp = 2 时必填】
    ben_id_card_back: '', //实际受益人身份证国徽面【ben_is_lp = 2 时必填】
    ben_name: '', //实际受益人姓名【ben_is_lp = 2 时必填】
    ben_id_card: '', //实际受益人身份证号码【ben_is_lp = 2 时必填】
    ben_id_card_start: '', //实际受益人身份证有效期开始日期【ben_is_lp = 2 时必填】
    ben_id_card_end: '', //实际受益人身份证有效期结束日期【ben_is_lp = 2 时必填】
    times: [],
    ben_id_card_is_long: 2, //实际受益人身份证有效期是否长期 1-是 2-否【ben_is_lp = 2 时必填】
    ben_id_card_area: '', //实际受益人身份证归属地区【ben_is_lp = 2 时必填】
    ben_id_card_address: '' //实际受益人身份证地址【ben_is_lp = 2 时必填】
});

/**
 * 商户信息ocr识别
 */
const corpLicenseOCR = (val = {}) => {
    if (!account_info.account_name && val.companyName) {
        account_info.account_name = val.companyName;
        enterpriseAccountInfoRef.value.formInfoRef?.clearValidate('account_name');
    }
};

/**
 * 取消
 */
const onBack = async () => {
    await ElMessageBox({
        message: h('div', null, [
            h('div', { class: 'box-main' }, [
                h('img', {
                    src: '//img.static-keyid.cn/toolspace/scrm/2023/10/1697424589039qtkjr2s9sb0yxsod.png!tumb'
                }),
                h('span', `取消后，当前填写的内容将不会保存，确认要取消吗？`)
            ])
        ]),
        customClass: 'account-detail-tips-box',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    });
    router.back();
};

/**
 * 返回列表
 */
const onBackList = () => {
    router.back();
};

/**
 * 保存草稿
 *
 */
const onSaveDraft = throttle(async () => {
    let list = ['corp_name', 'corp_abbreviation', 'corp_unified_social_credit_code'];
    let res = await enterpriseInfoRef.value.validate(list);

    if (res) {
        let data = await dataFormat();
        data.id = detailId.value;
        let r = await request('accountSaveDraftServ', data);
        ElMessage.success('草稿保存成功');
        router.back();
    }
}, 300);

/**
 * 提交材料
 */
const onSubmitData = async () => {
    // console.log(corp_info, '1');
    try {
        await enterpriseInfoRef.value.validate();
        await enterpriseAccountInfoRef.value.validate();
        await legalPersonInfoRef.value.validate();
        await contactsInfoRef.value.validate();
        await enterpriseControllerRef.value.validate();
        await enterpriseBeneficiaryRef.value.validate();
        // let promiseList = [
        //     enterpriseInfoRef.value.validate(),
        //     enterpriseAccountInfoRef.value.validate(),
        //     legalPersonInfoRef.value.validate(),
        //     contactsInfoRef.value.validate(),
        //     enterpriseControllerRef.value.validate(),
        //     enterpriseBeneficiaryRef.value.validate()
        // ];
        // await Promise.all(promiseList);
        await ElMessageBox({
            message: h('div', null, [
                h('div', { class: 'box-main' }, [
                    h('img', {
                        src: '//img.static-keyid.cn/toolspace/scrm/2023/10/1697424589039qtkjr2s9sb0yxsod.png!tumb'
                    }),
                    h('span', `提交后，填写的内容将无法修改，请认真检查后再提交。确定要提交吗？`)
                ])
            ]),
            customClass: 'account-detail-tips-box',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        });
        if (detailType.value == 'new') {
            await onSubmitNewSave();
        }
        if (detailType.value == 'edit') {
            await onSubmitEditSave();
        }
    } catch (err) {
        const [[errMessage]] = Object.values(err);
        let msgErr = errMessage?.message || '';
        msgErr &&
            ElMessage.warning({
                grouping: true,
                message: msgErr,
                repeatNum: 1
            });
    }
};

/**
 * 提交参数data处理
 */
const dataFormat = async () => {
    let data = {
        isp_code,
        capacity_code, // 产品能力
        corp_info: cloneDeep(corp_info),
        account_info: cloneDeep(account_info),
        lp_info: cloneDeep(lp_info),
        contact_info: cloneDeep(contact_info),
        ctl_info: cloneDeep(ctl_info),
        ben_info: cloneDeep(ben_info)
    };
    data.corp_info.corp_capital = String(corp_info.corp_capital);
    data.corp_info.corp_license_place = data.corp_info?.corp_license_place?.filter(el => el);

    if (data.corp_info.corp_times.length) {
        data.corp_info.corp_license_term_start = data.corp_info.corp_times[0];
        data.corp_info.corp_license_term_end = data.corp_info.corp_times[1];
    }
    if (data.lp_info.times.length) {
        data.lp_info.lp_id_card_start = data.lp_info.times[0];
        data.lp_info.lp_id_card_end = data.lp_info.times[1];
    }
    if (data.contact_info.times.length) {
        data.contact_info.contact_id_card_start = data.contact_info.times[0];
        data.contact_info.contact_id_card_end = data.contact_info.times[1];
    }
    if (data.ctl_info.ctl_is_lp == 2 && data.ctl_info.ctl_times.length) {
        data.ctl_info.ctl_id_card_start = data.ctl_info.ctl_times[0];
        data.ctl_info.ctl_id_card_end = data.ctl_info.ctl_times[1];
    }
    if (data.ctl_info.ctl_is_lp == 2 && data.ctl_info.ctl_corp_times.length) {
        data.ctl_info.ctl_corp_license_term_start = data.ctl_info.ctl_corp_times[0];
        data.ctl_info.ctl_corp_license_term_end = data.ctl_info.ctl_corp_times[1];
    }
    if (data.ben_info.ben_is_lp == 2 && data.ben_info.times.length) {
        data.ben_info.ben_id_card_start = data.ben_info.times[0];
        data.ben_info.ben_id_card_end = data.ben_info.times[1];
    }

    if (data.contact_info.contact_is_lp == 1) {
        let contactList = Object.keys(data.contact_info);
        contactList.forEach(el => {
            if (el != 'lp_email' && el != 'lp_mobile' && el != 'contact_is_lp') {
                data.contact_info[el] = undefined;
            }
        });
    } else if (data.contact_info.contact_is_lp == 2) {
        let contactList = Object.keys(data.contact_info);
        contactList.forEach(el => {
            if (el == 'lp_email' && el == 'lp_mobile') {
                data.contact_info[el] = undefined;
            }
        });
    }
    if (data.ctl_info.ctl_is_lp == 1) {
        let ctlList = Object.keys(data.ctl_info);
        ctlList.forEach(el => {
            if (el != 'ctl_is_lp') {
                data.ctl_info[el] = undefined;
            }
        });
    }
    if (data.ben_info.ben_is_lp == 1) {
        let benInfoList = Object.keys(data.ben_info);
        benInfoList.forEach(el => {
            if (el != 'ben_is_lp') {
                data.ben_info[el] = undefined;
            }
        });
    }
    if (corp_info.corp_main_type == 2) {
        if (account_info.account_type == 2) {
            data.account_info.account_name = '';
            data.account_info.account_public = '';
            data.account_info.account_bank = '';
            data.account_info.account_license = '';
        }
        if (account_info.account_type == 1) {
            data.account_info.account_private = '';
            data.account_info.account_bank_private = '';
            data.account_info.account_license_private = '';
        }
    }
    return data;
};

/**
 * 新建
 */
const onSubmitNewSave = async () => {
    let data = await dataFormat();

    // console.log(data, 'data');
    let res = await request('accountCreateServ', data);
    // isSubmitSuccess.value = true;
    detailId.value = res.data.id;
    window.removeEventListener('beforeunload', beforeUnloadHandler);
    router.replace({
        path: '/pay/account/dataSubSuccess',
        query: {
            id: detailId.value
        }
    });
};

/**
 * 编辑
 */
const onSubmitEditSave = async () => {
    let data = await dataFormat();
    data.id = detailId.value;
    let res = await request('accountEditServ', data);
    // isSubmitSuccess.value = true;
    detailId.value = res.data.id;
    window.removeEventListener('beforeunload', beforeUnloadHandler);
    router.replace({
        path: '/pay/account/dataSubSuccessEdit',
        query: {
            id: detailId.value
        }
    });
};

/**
 * 审核中事件
 * @param {*} type detail-查看详情，back-返回列表
 */
const onInReview = type => {
    if (type === 'detail') {
        detailType.value = 'look';
        isSubmitSuccess.value = false;
        getDetailInfo();
    } else if (type === 'back') {
        router.back();
    }
};

/**
 * 获取详情
 */
const getDetailInfo = async () => {
    let handle_type = detailType.value == 'look' ? 1 : detailType.value == 'edit' ? 2 : '';
    let params = {
        id: detailId.value,
        handle_type: handle_type // 操作类型 1-查看 2-编辑回显
    };
    let res = await request('accountEditViewServ', params);
    if (res.data?.isp_code) {
        isp_code = res.data.isp_code;
    }
    // 产品能力
    if (res.data?.capacity_code) {
        capacity_code = res.data.capacity_code;
    }
    if (res.data?.is_edit == 2) {
        detailType.value = 'look';
        window.removeEventListener('beforeunload', beforeUnloadHandler);
    }
    baseInfo.value = res.data.basic_merchant_info || {};
    Object.assign(corp_info, res.data.corp_info);
    Object.assign(account_info, res.data.account_info);
    Object.assign(lp_info, res.data.lp_info);
    Object.assign(contact_info, res.data.contact_info);
    Object.assign(ctl_info, res.data.ctl_info);
    Object.assign(ben_info, res.data.ben_info);

    if (corp_info.corp_license_term_start && corp_info.corp_license_term_end) {
        corp_info.corp_times = [corp_info.corp_license_term_start, corp_info.corp_license_term_end];
    }
    if (lp_info.lp_id_card_start && lp_info.lp_id_card_end) {
        lp_info.times = [lp_info.lp_id_card_start, lp_info.lp_id_card_end];
    }
    if (contact_info.contact_id_card_start && contact_info.contact_id_card_end) {
        contact_info.times = [contact_info.contact_id_card_start, contact_info.contact_id_card_end];
    }
    if (account_info.account_bank) {
        let { account_bank, account_bank_name } = account_info;
        enterpriseAccountInfoRef.value.accountBankOption = [
            {
                value: account_bank,
                label: account_bank_name
            }
        ];
    }
    if (account_info.account_bank_private) {
        let { account_bank_private, account_bank_private_name } = account_info;
        enterpriseAccountInfoRef.value.accountBankPrivateOption = [
            {
                value: account_bank_private,
                label: account_bank_private_name
            }
        ];
        enterpriseAccountInfoRef.value.bankPrivateName = account_bank_private_name;
    }

    if (ctl_info.ctl_is_lp == 2 && ctl_info.ctl_id_card_start && ctl_info.ctl_id_card_end) {
        ctl_info.ctl_times = [ctl_info.ctl_id_card_start, ctl_info.ctl_id_card_end];
    }
    if (ctl_info.ctl_is_lp == 2 && ctl_info.ctl_corp_license_term_start && ctl_info.ctl_corp_license_term_end) {
        ctl_info.ctl_corp_times = [ctl_info.ctl_corp_license_term_start, ctl_info.ctl_corp_license_term_end];
    }
    if (ben_info.ben_is_lp == 2 && ben_info.ben_id_card_start && ben_info.ben_id_card_end) {
        ben_info.times = [ben_info.ben_id_card_start, ben_info.ben_id_card_end];
    }
};

const beforeUnloadHandler = event => {
    event.returnValue = '刷新页面后，当前填写的内容将会清空，请谨慎操作！';
    return;
};

onMounted(() => {
    if (detailType.value == 'look' || detailType.value == 'edit') {
        getDetailInfo();
    }
    nextTick(() => {
        if (detailType.value == 'new' || detailType.value == 'edit') {
            window.addEventListener('beforeunload', beforeUnloadHandler);
        }
    });
});

onUnmounted(() => {
    window.removeEventListener('beforeunload', beforeUnloadHandler);
});
</script>
<style lang="scss">
.account-detail-tips-box {
    padding-bottom: 16px;
    background: #ffffff;
    width: 490px;
    min-width: 490px;
    box-shadow: 0px 12px 48px 16px rgba(0, 0, 0, 0.03), 0px 9px 28px 0px rgba(0, 0, 0, 0.05),
        0px 6px 16px -8px rgba(0, 0, 0, 0.08);
    .el-message-box__content {
        padding: 33px 28px 47px;
    }
    .box-main {
        display: flex;
        line-height: 24px;
        img {
            width: 24px;
            height: 24px;
            margin-right: 8px;
        }
        span {
            font-size: 16px;
            font-weight: 500;
            color: #33302d;
        }
    }
    .el-message-box__btns {
        padding-right: 24px;
    }
}
</style>
<style lang="scss" scoped>
.content-detail {
    // height: calc(100vh - 207px);
    min-width: 948px;
    margin-bottom: 80px;
    :deep(.el-form-item__error) {
        padding-top: 4px;
    }
}
.footer-info {
    min-width: 948px;
    position: absolute;
    left: 200px;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 16px 24px;
    border-radius: 0;
    border: none;
    border-top: 1px solid #e4e7ed;
    background-color: #fff;
    z-index: 2001;
}
</style>
